#include "spi.h"


uint8_t spi1_send(uint8_t data, uint8_t read){
    uint8_t ret=0;

    (void)SPI1->DR;
    
    while((SPI1->SR & SPI_SR_TXE) == 0){__NOP();};
    SPI1->DR = data;
    while((SPI1->SR & SPI_SR_RXNE) == 0){__NOP();};
    ret=SPI1_DR_8b;

    return ret;
}


void spi1_init(void){

    spi1_gpio_init();

    //84Mhz
    RCC->APB2ENR |= RCC_APB2ENR_SPI1EN;

    SPI1->CR1 = 0;
    SPI1->CR1 = SPI_CR1_SSI|SPI_CR1_SSM |\
               /* SPI_CR1_CPHA|SPI_CR1_CPOL |\ */
                SPI_CR1_MSTR |\
                (0 << SPI_CR1_BR_Pos);

	SPI1->CR1 |= SPI_CR1_SPE;
}

/*
PB3 SCK
PB5 MOSI
PB4 MISO
PA15 CS
*/
void spi1_gpio_init(void){

    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN|RCC_AHB1ENR_GPIOEEN;

    //PB3,PB4,PB5
    GPIOA->MODER &= ~(GPIO_MODER_MODE5|GPIO_MODER_MODE6|GPIO_MODER_MODE7);
    GPIOA->MODER |= (GPIO_MODER_MODE5_1|GPIO_MODER_MODE6_1|GPIO_MODER_MODE7_1);

    GPIOA->OTYPER &= ~(GPIO_OTYPER_OT5|GPIO_OTYPER_OT6|GPIO_OTYPER_OT7);

    GPIOA->OSPEEDR |= (3 << GPIO_OSPEEDR_OSPEED5_Pos)| (3 << GPIO_OSPEEDR_OSPEED6_Pos)|(3 << GPIO_OSPEEDR_OSPEED7_Pos);

    GPIOA->PUPDR &= ~(GPIO_PUPDR_PUPD3|GPIO_PUPDR_PUPD4|GPIO_PUPDR_PUPD5);

    GPIOA->AFR[0] &= ~(GPIO_AFRL_AFRL5|GPIO_AFRL_AFRL6|GPIO_AFRL_AFRL7);
    GPIOA->AFR[0] |= (5 << GPIO_AFRL_AFSEL5_Pos)|(5 << GPIO_AFRL_AFSEL6_Pos)|(5 << GPIO_AFRL_AFSEL7_Pos);

    //PA15 CS
    GPIOA->MODER &= ~GPIO_MODER_MODE4;
  	GPIOA->MODER |= GPIO_MODER_MODE4_0;
	
    GPIOA->OSPEEDR |= (3 << GPIO_OSPEEDR_OSPEED4_Pos);
	
    GPIOA->PUPDR &= ~GPIO_PUPDR_PUPD4;

        //PE4
    GPIOE->MODER &= ~GPIO_MODER_MODE4;
    GPIOE->MODER |= GPIO_MODER_MODE4_0;
      
    GPIOE->OSPEEDR |= (3 << GPIO_OSPEEDR_OSPEED4_Pos);
      
    GPIOE->PUPDR &= ~GPIO_PUPDR_PUPD4;
    GPIOE->BSRR = GPIO_BSRR_BR4;

//开灯
    GPIOA->MODER &= ~GPIO_MODER_MODE2;
    GPIOA->MODER |= GPIO_MODER_MODE2_0;
  
    GPIOA->OSPEEDR |= (3 << GPIO_OSPEEDR_OSPEED2_Pos);
  
    GPIOA->PUPDR &= ~GPIO_PUPDR_PUPD2;

    GPIOA->BSRR = GPIO_BSRR_BS2;

    SPI1_CS_HI;
}   